<?php

namespace app\service;

use app\model\Products;
use app\model\SellerCategories;
use app\model\Sellers;
use app\model\ShopFavorite;
use app\model\ShopReview;

class ShopService
{
    public function getShopInfo($id)
    {
        //   id: 1,
        // name: '旅行喵精选店铺',
        // avatar: '/static/image/default_avatar.png',
        // bannerImages: [
        //   '/static/image/banner1.jpg',
        //   '/static/image/banner2.jpg',
        //   '/static/image/mars1.jpg'
        // ],
        // tags: ['官方认证', '金牌商家', '7天退换'],
        // rating: 4.8,
        // reviewCount: 1256,
        // productCount: 128,
        // followerCount: 5680,
        // salesCount: 12580
        if (empty($id)) {
            return $this->getPlatform();
        }

        $shop = $this->getShop($id);
        return $shop;
    }

    protected function getPlatform()
    {

        $platform = [
            'id' => 0,
            'store_name' => '喵旅',
            'logo' => '/static/logo.png',
            'bannerImages' => [],
            'tags' => ['官方认证', '平台自营', '品质保证'],
            'rating' => 5,
            'reviewCount' => 0, //评价数
            'productCount' => Products::whereIsNull('seller_id')->whereOr('seller_id', 0)->count(),
            'followerCount' => ShopFavorite::where('shop_id', 0)->count() ?? '999+',
            'salesCount' => Products::whereIsNull('seller_id')->whereOr('seller_id', 0)->sum('sales') ?? '999+',
            'is_followed' => true
        ];
        $platform['banner_images'] = array_map(function ($item) {
            return env('IMAGE_URL') . $item;
        }, $platform['banner_images']);
        return $platform;
    }

    protected function getShop($id)
    {
        $uid = UserService::getCurrentUserId();
        $shop = Sellers::where('id', $id)->with('sellerGroups')->find();
        $shop = [
            'id' => $shop->id,
            'store_name' => $shop->store_name,
            'logo' => env('IMAGE_URL') . $shop->logo,
            'banner_images' => empty($shop->banner) ? [] : explode(',', $shop->banner),
            'tags' => ['官方认证', '品质商家'], //$shop->sellerGroups->pluck('name')->toArray(),
            'rating' => 4.5,
            'review_count' => ShopReview::where('shop_id', $id)->count(), //评价数
            'product_count' => Products::where('seller_id', $id)->count(),
            'follower_count' => ShopFavorite::where('shop_id', $id)->count() ?? '0',
            'sales_count' => Products::where('seller_id', $id)->sum('sales') ?? '0',
            'is_followed' => ShopFavorite::where('shop_id', $id)->where('user_id', (int)$uid)->count() > 0 ? true : false,
        ];
        $shop['banner_images'] = array_map(function ($item) {
            return env('IMAGE_URL') . $item;
        }, $shop['banner_images']);

        $shop['cate_list'] = SellerCategories::where('seller_id', $id)
            ->where('parent_id', 0)
            ->where('active', 1)
            ->with('cateDescriptions')
            ->order(['position' => 'asc', 'id' => 'asc'])
            ->select()->toArray();
        //type goods
        // 插入全部
        $originCate = $shop['cate_list'];
        $shop['cate_list'] = [];
        $shop['cate_list'][] = [
            'id' => 0,
            'parent_id' => 0,
            'type' => 'goods',
            'cateDescriptions' => [
                'name' => '全部',
            ],
        ];
        // 合并
        $shop['cate_list'] = array_merge($shop['cate_list'], $originCate);
        $shop['cate_list'] = array_map(function ($item) {
            $item['type'] = 'goods';
            $item['name'] = $item['cateDescriptions']['name'];
            return $item;
        }, $shop['cate_list']);
        return $shop;
    }

    public function getShopProduct($query)
    {
        // http://127.0.0.1:8888/api/v1/shop/product?shop_id=1&minPrice=12&maxPrice=33&sortBy=price_desc&shop_cate_id=100000
        $shopId = $query['shop_id'];
        $minPrice = $query['minPrice']??'';
        $maxPrice = $query['maxPrice']??'';
        $sortBy = $query['sortBy']??'default';
        $shopCateId = $query['shop_cate_id']??'';
        $searchKeyword=$query['keyword']??'';
        $uid = UserService::getCurrentUserId();

        $where = [];
        $skuWhere = [];
        if($searchKeyword){
            $where[] = ['a2.name','like','%'.$searchKeyword.'%'];
        }
        if($minPrice){
            $where[] = ['a3.price', '>=', $minPrice];
        }
        if($maxPrice){
            $where[] = ['a3.price', '<=', $maxPrice];
        }
        if($shopCateId){
            $where[] = ['a4.category_id', '=', $shopCateId];
        }
        if($sortBy){
            if($sortBy == 'price_desc'){
                $order = ['a3.price' => 'desc'];
            }elseif($sortBy == 'price_asc'){
                $order = ['a3.price' => 'asc'];
            }elseif ($sortBy == 'sales'){
                $order = ['a1.sales' => 'desc'];
            }else{
                $order = ['a1.position_seller' => 'asc'];
            }
        }
        // $where[] = ['a3.is_default', '=',1];
        // 优化联表查询逻辑
        $shopProduct = Products::alias('a1')
            ->leftJoin('product_descriptions a2', 'a1.id=a2.product_id AND a2.locale="zh_cn"')
            ->leftJoin('product_skus a3', 'a1.id=a3.product_id AND a3.is_default=1')
            ->leftJoin('product_categories a4','a1.id=a4.product_id')
            ->where('a1.seller_id', $shopId)
            ->where($where)
            ->field('a1.id,a1.brand_id,a1.images,a1.price,a1.sales,a1.position_seller,a1.shore_desc,a1.product_type,a1.lable_tag,a1.give_points,a1.product_sn,a1.mark_icon,a1.mini_icon,a1.spot_id,a1.mini_qr_img,a2.name,a3.price as sku_price')
            ->order($order)
            ->select()
            ->toArray();
        
        // 如果有价格筛选条件，需要额外处理
        if(!empty($skuWhere)){
            $shopProduct = array_filter($shopProduct, function($item) use ($skuWhere){
                $price = $item['sku_price'] ?? $item['price'];
                foreach($skuWhere as $condition){
                    if($condition[1] == '>=' && $price < $condition[2]) return false;
                    if($condition[1] == '<=' && $price > $condition[2]) return false;
                }
                return true;
            });
        }
        $shopProduct = array_map(function ($item) {
            $item['image'] = empty($item['images']) ? [] : $item['images'][0];
            $item['image'] = env('IMAGE_URL') . $item['image'];
            $item['price'] = $item['sku_price'];
            return $item;
        }, $shopProduct);
        $shopProduct=array_values($shopProduct);
        return $shopProduct;
    }


    // 取消关注、关注店铺
    public function toggleFollow($id)
    {
        $uid = (int)UserService::getCurrentUserId();
        $shopFavorite = ShopFavorite::where('shop_id', $id)->where('user_id', $uid)->find();
        if ($shopFavorite) {
            $shopFavorite->delete();
            return false;
        }
        $shopFavorite = new ShopFavorite();
        $shopFavorite->shop_id = $id;
        $shopFavorite->user_id = $uid;
        $shopFavorite->created_at = date('Y-m-d H:i:s');
        $shopFavorite->save();
        return true;
    }

    // 获取评价
    public function getShopReviews($id)
    {
        $shopReviews = ShopReview::where('shop_id', $id)
        ->limit(10)
        ->order(['id'=>'desc'])
        ->with(['user'=>function($query){
            $query->field('id,name as username,avatar');
        }])
        ->select()
        ->toArray();
        return $shopReviews;
    }
}
